package com.example.chatzsyproject.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpClientUtils {
    /**
     * 懒汉 安全 加同步
     * 私有的静态成员变量 只声明不创建
     * 私有的构造方法
     * 提供返回实例的静态方法
     */
    private static OkHttpClient okHttpClient = null;

    @SuppressLint("HandlerLeak")
    private static Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            HttpResult http = (HttpResult) msg.obj;

            if (msg.what == 1) {
                Bundle data = msg.getData();
                String json = data.getString("json");
                http.succ(json);
            } else {
                http.error();
            }
        }
    };

    private String TAG = "wsy";


    private OkHttpClientUtils() {
    }

    public static OkHttpClient getInstance() {
        if (okHttpClient == null) {
            //加同步安全
            synchronized (OkHttpClientUtils.class) {
                if (okHttpClient == null) {
                    //okhttp可以缓存数据....指定缓存路径
                    File sdcache = new File(Environment.getExternalStorageDirectory(), "cache");
                    //指定缓存大小
                    int cacheSize = 10 * 1024 * 1024;

                    okHttpClient = new OkHttpClient.Builder()//构建器
                            .proxySelector(new ProxySelector() {
                                @Override
                                public List<Proxy> select(URI uri) {
                                    return Collections.singletonList(Proxy.NO_PROXY);
                                }

                                @Override
                                public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {

                                }
                            })
                            .connectTimeout(15, TimeUnit.SECONDS)//连接超时
                            .writeTimeout(20, TimeUnit.SECONDS)//写入超时
                            .readTimeout(20, TimeUnit.SECONDS)//读取超时
//                            .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize))//设置缓存
                            .build();
                }
            }

        }

        return okHttpClient;
    }

    /**
     * get请求
     * 参数1 url
     * 参数2 回调Callback
     */

    public static void doGet(Context context, String oldUrl, Callback callback) {

        Map<String, String> map = new HashMap<>();

        StringBuilder stringBuilder = new StringBuilder();//创建一个stringBuilder

        stringBuilder.append(oldUrl);

        if (oldUrl.contains("?")) {
            //?在最后面....2类型
            if (oldUrl.indexOf("?") == oldUrl.length() - 1) {

            } else {
                //3类型...拼接上&
                stringBuilder.append("&");
            }
        } else {
            //不包含? 属于1类型,,,先拼接上?号
            stringBuilder.append("?");
        }

        //添加公共参数....
        for (Map.Entry<String, String> entry : map.entrySet()) {
            //拼接
            stringBuilder.append(entry.getKey())
                    .append("=")
                    .append(entry.getValue())
                    .append("&");
        }

        //删掉最后一个&符号
        if (stringBuilder.indexOf("&") != -1) {
            stringBuilder.deleteCharAt(stringBuilder.lastIndexOf("&"));
        }

        String newUrl = stringBuilder.toString();//新的路径

        //创建OkHttpClient请求对象
        OkHttpClient okHttpClient = getInstance();
        //创建Request
        Request request = new Request.Builder().url(newUrl).build();
        //得到Call对象
        Call call = okHttpClient.newCall(request);
        //执行异步请求
        call.enqueue(callback);


    }

    /**
     * post请求
     * 参数1 url
     * 参数2 Map<String, String> params post请求的时候给服务器传的数据
     * add..("","")
     * add()
     */

    public static void doPost(String url, Map<String, String> params, final HttpResult http) {

        Log.e("zsy", "请求参数= " + new Gson().toJson(params));

        //创建OkHttpClient请求对象
        OkHttpClient okHttpClient = getInstance();
        //3.x版本post请求换成FormBody 封装键值对参数
        final FormBody.Builder builder = new FormBody.Builder();
        //遍历集合
        Set<String> keys = params.keySet();
        for (String key : keys) {
            builder.add(key, params.get(key));
        }

        //添加公共参数
//        for (Map.Entry<String, String> entry : map.entrySet()) {
//            builder.add(entry.getKey(), entry.getValue());
//        }

        //创建Request
        Request request = new Request.Builder().url(url).post(builder.build()).build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                http.error();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Log.e("zsy","请求结果="+string);
                Message msg = new Message();
                Bundle bundle = new Bundle();
                bundle.putString("json", string);
                msg.setData(bundle);
                msg.obj = http;
                msg.what = 1;
                handler.sendMessage(msg);
            }
        });
    }

}
